1. 题目描述(简单难度)

[success] 652. 寻找重复的子树

2. 解法一:DFS二叉树序列化

class Solution {
    Map<String,Integer> map = new HashMap<>();
    List<TreeNode> resp = new ArrayList<>();
    public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
        if(root == null){
            return new ArrayList<>();
        }
        preOrderSerial(root,new StringBuilder());
        return resp;
    }

    public String preOrderSerial(TreeNode root,StringBuilder sb){
        if(root == null){
           return "#";
        }

        sb.append(root.val).append(",").append(preOrderSerial(root.left,new StringBuilder())).append(",").append(preOrderSerial(root.right,new StringBuilder()));

        map.put(sb.toString(),map.getOrDefault(sb.toString(),0)+1);

        if(map.get(sb.toString()) == 2){
            resp.add(root);
        }
        return sb.toString();
    }
}
© gaohueric all right reserved,powered by Gitbook文件修订时间: 2021-12-08 23:22:22

results matching ""

    No results matching ""